
package com.fattyCorps.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

public class JwtUtils {
    // 秘钥
    private static final String JWT_SECRET = "vcf&*sgh$ff";

    // 根据用户id与username生成token
    public static String createToken(String idName, int id, String secret) {
        // 签发时间
        Calendar ins = Calendar.getInstance();
        ins.add(Calendar.SECOND, 24 * 60 * 60);

        // 秘钥加密方式
        Algorithm algorithm = Algorithm.HMAC256(secret);

        String token = JWT.create()
                .withClaim(idName, id)
                .withExpiresAt(ins.getTime())
                .sign(algorithm);

        return token;
    }

    // 获取token信息
    public static DecodedJWT verify(String token, String secret) {
        return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
    }

    public static Integer getIdByRequest(HttpServletRequest request, String idName, String secret) {
        String token = request.getHeader("token");
        if (token == null) {
            return 0;
        }

        return getIdByToken(token, idName, secret);
    }

    public static Integer getIdByToken(String token, String idName, String secret) {
        DecodedJWT decodedJWT;
        try {
            decodedJWT = JwtUtils.verify(token, secret);
        } catch (Exception e) {
            return 0;
        }

        Integer id = decodedJWT.getClaim(idName).asInt();
        if (id == null) {
            return 0;
        }

        return id;
    }

}